//namespaces - tied to data model
var dtns = "http://www.dshlt.com/tabs";
var dwns = "http://www.dshlt.com/widgets";
var dins = "http://www.dshlt.com/item";
var duns = "http://www.dshlt.com/user";

var ctxt = new Object();
ctxt.prefs = new Object();
ctxt.dshltSettings = new Object();
ctxt.tid = "";
ctxt.tabs = new Object();
ctxt.registers = new Object();
ctxt.registers.f = new Object();


//widget cookie variable - required for dashboard widgets in order to set cookies
//used by oxQuery
var gWidgetCookie = null;

var oxUtil = function() {

    //private variables
    var VERSION = "1.0";
    
    var widgetTypeTool = ["search", "mystarred", "myrecent"]

    var debugFooter = null;
     
    //script request counter
    var scriptCounter = 1;

    return {

        /*** OBJECT UTILITIES ***/
    	getVersion : function() {
    	   return VERSION;
    	}
		,
		
		//this is used by landing pages to see if there is a hash attached to the url and redirect to it if appropriate
		//hashing is used by the application to identify sub pages without doing proper url rewriting
		//the hash identifies the actual page we are trying to reach
		checkURL : function() {
			var hash = window.location.hash;
			if (hash.indexOf("/lib/item/item-view-detail.xqy") > -1)
			window.location = hash.substring(1);
		}
		
		,
    	/***** FORM MANAGEMENT *****/
    	// in html: <input type="text" onKeyPress="if(oxUtil.inputKeyCheck(event)) !!!do form action!!!"> 
    	inputKeyCheck : function (e) {
    	   //FROM: http://jennifermadden.com/javascript/stringEnterKeyDetector.html
    	   // No licensing indicated 
    	   // - was missing one comment indicator    
    	   // - was missing some syntax: semicolons
    	   // - changed the name
    	   // - fixed misuse of e and event
    	    
    	   //e is event object passed from function invocation	   
           var characterCode;  //literal character code will be stored in this variable
            if(e && e.which){ //if which property of event object is supported (NN4)
                 characterCode = e.which; //character code is contained in NN4's which property
            } else {
                 characterCode = e.keyCode; //character code is contained in IE's keyCode property
            }
        
            if(characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
               return true;
            } else {
               return false;
             }
        }
        
      	
    	,
    	/***** DEBUG *****/
        debug : function (msg) {
            try { 
             console.log(msg);
            } catch (e) {}
//            if (!msg) msg = "no message";
//            if (debugFooter) {
//                //nothing, will assign below
//            } else {
//                debugFooter = document.getElementById("debugFooter");
//            }
//            try {
//                 debugFooter.innerHTML = debugFooter.innerHTML + "<div class='debugFooterEntry'>" + oxUtil.getDateTime() + ": " + msg + "</div>";
//            } catch (e) {
//                //nothing - no debug footer was available
//            }
            return;
        }
    	,
    	/***** DATE TIME *****/
    	//returns the current datetime as UTC with 00:00 offset
    	//the time returned takes into account the offset so you should see time equivalent to GMT/UTC
    	//if format is "ml" returns it in a Marklogic format
    	//if format is null returns the standard JavScript UTC format which is implementation dependent
    	getDateTime : function (format) {
    	    var d = new Date();
    	    var ds = "";
    	    if (format =="ml") {
    	       var month = d.getUTCMonth()+1;
    	       if (month<10) {month = "0" + month;}
    	       var day = d.getUTCDate();
    	       if (day<10) {day = "0" + day;}
    	       var hours = d.getUTCHours();
    	       if (hours<10) {hours = "0" + hours;}
    	       var minutes = d.getUTCMinutes();
    	       if (minutes<10) {minutes = "0" + minutes;}
    	       var seconds = d.getUTCSeconds();
    	       if (seconds<10) {seconds = "0" + seconds;}
    	       var msec = d.getUTCMilliseconds();
    	       if (msec<10) {msec = "00" + msec;}
    	       else if (msec<100) {msec = "0" + msec;}
    	       ds = d.getFullYear()+"-"+
    	            month+"-"+
    	            day+"T"+
    	            hours+":"+
    	            minutes+":"+
    	            seconds+"."+
    	            msec+
    	            "-00:00";
    	    } else {
    	       ds = d.toUTCString();
    	    }
    	    return ds;
    	}
    	,

    	/**** QUOTE/UNQUOTE STRINGS *****/
    	unquote : function (t) {
    	    if (t != null) {
    	       t = t.replace(/&lt;/g,"<");
    	       t = t.replace(/&gt;/g,">");
    	       t = t.replace(/&amp;/g,"&");
    	       t = t.replace(/&apos;/g,"'");
    	       t = t.replace(/&quot;/g,'"');
    	    } else {
    	        t = "";
    	    }
    	    return t;
    	}
    	
    	,
    	
    	quote : function (t) {
    	    if (t != null) {
        	    t = t.replace(/</g, "&lt;");
        	    t = t.replace(/>/g, "&gt;");
    	    } else {
    	        t="";
    	    }
    	    return t;
    	}
    	,
    	
    	/**** DISPLAY AND PARSE XML/DOM *****/
        xmlParse : function (t) {
            try {    
                if (typeof DOMParser != "undefined") {
                    return (new DOMParser()).parseFromString(t, "application/xml");
                } 
                else if (typeof ActiveXObject != "undefined") {
//t = "<first><second>sec</second><third>thi</third></first>"
//alert("ie test b1" + t);  
                    //var doc = XML.newDocument();
                    var doc = new ActiveXObject("MSXML2.DOMDocument");

                    doc.loadXML(t);
//alert("ie test b2 cn---" + doc.childNodes);
//alert("ie test b3a doc ele---" + doc.documentElement );
//alert("ie test b3b doc ele tn---" + doc.documentElement.tagName );
//alert("ie test b4 doc ele xml---" + doc.documentElement.xml);
//alert("ie test b5a doc ele cn---" + doc.documentElement.childNodes);
//alert("ie test b5b doc ele cn 0 tn ---" + doc.documentElement.childNodes[0].tagName);
//var n = doc.getElementsByTagName("itemui");
//alert("ie test b5c doc ele gebtn length---" + n.length);
//alert("ie test b5d doc ele gebtn n[0] xml---" + n[0].xml);
                    return doc;
                }
            } catch (e) {
                alert(e);
                alert(e.message);
            }
        }
        
        ,
        
        domSerialize : function (node) {
            if (typeof XMLSerializer != "undefined" ) {
                return (new XMLSerializer()).serializeToString(node);
            } else if (node.xml) return node.xml;
            else return "Cannot serialize DOM to XML string - method not supported"; 
        }
        ,
        
        checkWidgetTypeTool:function (t) {
            for (var i = 0; i < widgetTypeTool.length; i ++) {
                if (t == widgetTypeTool[i])
                return true;
            }
            return false;
        }
        ,
        /***** display of ui elements *****/
        setDisplay:function (elem, disp) {
        	var s = elem.getAttribute("style");
        	elem.setAttribute("style",s+";"+disp);
        	return;
        }        
        ,
        /***** EXECUTE XPATH *****/
        /* FF/IE BROWSER DEPENDENT */
        // rn is the context node - where to begin the search from
        // xp is the xpath expression as a string
        xpath:function (rn, xp) {
           var ret = null;
           //FF
           if (document.createExpression) {
               //alert(document.evaluate("/", document, null, 0, null));
               //had replace rn with document when using DOCTYPE and executing
               //unknown why - FF was returning an error NS_ERROR_DOM_NOT_SUPPORTED_ERR
               var res =
                   document.evaluate(
                      xp,
                      document,
                      null,
                      XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
                      null
                   );
           
               var ret = new Array(res.snapshotLength);
               for (var i=0;i < res.snapshotLength; i++ ) {
                   ret[i] = res.snapshotItem(i);
               }
           } else {
               //IE
           }
           
           return ret; 
        }
        ,
        
        /***** SCRIPT MANAGEMENT *****/
        scriptRequest:  function (fu) {
              
          // HTTP path to the "script"
         var fullUrl = fu;
         if ( (fullUrl.indexOf("http")) < 0 ) { fullUrl = "http://" + oxEnv.getHost() + fullUrl; }
         if ( (fullUrl.indexOf("?")) < 0 ) { fullUrl = fullUrl + "?var=novar"; }
         
          // Keep IE from caching requests
          var noCacheIE = '&noCacheIE=' + (new Date()).getTime();
          // Get the DOM location to put the script tag
          var headLoc = document.getElementsByTagName("head").item(0);

          // Generate a unique script tag id
          var scriptId = 'YJscriptId' + scriptCounter++;
          
          //create the script obj for later use
          var scriptObj = null;
          

          return {
              
            // buildScriptTag method
            buildScriptTag : function (noLoadCheck) {
                var debug = false;
                if (debug) oxUtil.debug("buildScriptTag()");
                // Create the script tag
                scriptObj = document.createElement("script");
    
                // Add script object attributes
                var src = fullUrl +noCacheIE;
                scriptObj.setAttribute("type", "text/javascript");
                scriptObj.setAttribute("charset", "utf-8");
                scriptObj.setAttribute("language", "Javascript");
                scriptObj.setAttribute("src", src);
                scriptObj.setAttribute("id", scriptId);
                if (noLoadCheck) {
                    //do not add onload
                    // the onload attribute will set variables to manage the loading of the script
                    // so that the widgets which load scripts will not get too far without having their scripts loaded
                    //scriptObj.setAttribute("onload","oxUtil.debug('script loaded');");
                } else {
                    //scriptObj.onload = function(){oxUtil.debug("dog");}
                    scriptObj.setAttribute("onload","scriptLoaded('"+ctxt.tid+"','"+fu+"', 'true');");
                    scriptObj.setAttribute("onreadystatechange","ctxt.tabs["+ctxt.tid+"].loadedScripts['"+fu+"'].loaded='true';scriptLoaded('"+ctxt.tid+"','"+fu+"')");
                }
             }
            ,
                        
            // addScriptTag method
            addScriptTag : function () {
                var debug = false;
                if (debug) oxUtil.debug("addScriptTag(): start");
              // Create the script tag
              headLoc.appendChild(scriptObj);
              
              if (debug)  oxUtil.debug("addScriptTag(): finish" );
            }
            ,
            
            // removeScriptTag method
            removeScriptTag : function () {
              var debug = false;
              if (debug) oxUtil.debug("removeScriptTag()");
              // Destroy the script tag
              headLoc.removeChild(scriptObj);
            }

            
          } 
          
        }

    }

} ();